package edu.capex.javaee.sockets;

import java.io.*;



import java.net.*;

class jabberclientthread extends Thread {

    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    public static int counter = 0;
    private int id = counter++;
    private static int threadcount = 0;

    public static int threadCount() {
        return threadcount;
    }

    public jabberclientthread(InetAddress addr) {
        System.out.println("Making client" + id);

        threadcount++;

        try {
            socket = new Socket(addr, MultijabberServer.PORT);
        } catch (Exception e) {
        }

        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            start();
        } catch (IOException e) {
            try {
                socket.close();
            } catch (IOException e2) {
            }
        }
    }

    public void run() {
        try {
            for (int i = 0; i < 25; i++) {
                out.println("client" + id + ":" + i);
                String str = in.readLine();
                System.out.println(str);
            }
            out.println("END");
        } catch (IOException e) {
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
            }
            threadcount--;
        }
    }
}

public class multijabberclient {

    static final int Max_threads = 40;

    public static void main(String args[]) throws IOException {
        InetAddress addr = InetAddress.getByName(null);
        while (true) {
            if (jabberclientthread.threadCount() < Max_threads) {
                new jabberclientthread(addr);
            }
        }
    }
}
